package com.junjun.ssm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.junjun.ssm.dao.OrderDao;
import com.junjun.ssm.entity.OrderEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PayController {

    @Autowired
    OrderDao orderDao;
    //appid
    private final String APP_ID = "2021000122614727";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCS0x2U/YlmBA2FdDU6Ge7Q8rfgczjDnLqalKJOoP6Kv4++H6b6qKOxtQktmym3nnlBaTcO/yHIJcMl4Xl/jNavP1v+mtMEUSpGPhfxU4LKCJJqWH63jaPsAMvEGkprdDyG1qpYiszOEvm5vU+tUhrPqIs57oDZaVRGAFMc90Zh9DqLN5wJvJ4Ep1kBQvMa7W2YvOzfiSH43wzHjn7uXFUj+JB4N8Vrlc+jDZV3gGU7rFPZJVLHE+GRdHTf28ma9z573gnUpNEmnSwCB9CTQ8KGyh2B9P3QjcYip6LABEyIY6hNHe86oCVLyB0goUKYY0T1i6H5gOJCjqHbqjX2c6b5AgMBAAECggEAGP7R2Wx0OKbV+nM3IIYLrwyzGwXikwKajfhhzUsBKnPEL9TJo4CUJYuxXU8+AeF7uRQFaIssoBs1prxE5979KWZ67dRDukdrD/xALThPWr+s1WftYqg9UM8t4VuscbCfIUFoTJyMk0SNuP4uk04X/GQwF5Ov4dNZonUpsROzqrcb9sUe5GUGRAY+Kfvp0+Xct9YpR/V9IH7EEqyD+4+UKpfMWSjWwrDgtEvMaYVBRUtgS1YTbRz2QEnnqFD+JEGcQDQT5UEeLbxBx0O83krpNSzNyAnFzdJSE9qkB3r1rsrAldd6jC9lIsw3X0zqG81g7Uvo1Dzz0jdAdjGQjeAogQKBgQDU/DKMoMcl7q8mzSs5PI3mMmtEtqo5iHTWEK/93HZ+5vC1+gcr+kNY1KZYPA95bzyNV8A5T5RxQ2pwIEzW3Ob/5qOLPMCL4m93CuFlKTmnF/JiVphjkm8M5swHecJh8siblS5ZDtmK3nUE7kxvQLROLmdnn/OKXahzA41hwQ7caQKBgQCwekZ8HNn3LakH3UQhIGTKy/gZUqLnec1NGUpsat3V0kpN4q+IxbM3D3blABzDQ8KMXmr6meJBZianysOBV2OjhfZeKgGzCim5v7+ZU7IlhuOYRfcqTVpQjbufoZpMMvogRvO7ExxpOmDJ9uWIInB3pVLxCVFRNpUf9ygrb65kEQKBgQC9J25NbszvZ1evAjANGTZ85vJViFUN257ILvHeZ9nlQn0tYOzVpeICFnnViyHDG4OPlAtn2sFfBhyVkFotyOpvAwrkMgRfN67+7m7XRRGq0J23sGiOphJyRteVHBICo3h+lLMg7QtPRdpvkqPXeoOnm5bCdU/55swfuVvrIWZtYQKBgHfm6+LBe3oMJM76D6LuLmz2vh7+XT4mLE2YxE77ILN5CBD41kh4AjaDpEUcmW41qIXUVJzlVqsWa2cPRVuoc0MT7nq10afCXO0eEWBsVBpZFmNMDg1ItvcKBRMFKh9hdz3c1xYgeuonxsERpYuj0oQH6F1p9jzWd+Va+IjifTrxAoGBAI+zE36ya1baL41az9VCsMMYM5DSRJwyFd27D0/0c45SO7CNdv2yGtRpXN9EGg3ikdNxX9ET7eFytdJ3aGDyA5xZe0MG+QBHFCVZAjmDnpe7nO3PwPXpp29fe8hDligQy6d0FqnNgGonchGepE1Igbz8hk0Lww6DN+qCr3ZKUtoN";

    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvMphcHETsPzaTXbcL/+HyrCGrJ3MiTGsvZ7xZBt/TE4lYf0Irx+crZeKHIF8pDgRKgBJYSu02JABmpqi36qdyGq+graeDLDDTArxiNIQ7KERYpGNcnF+ysLoqKSCMZ31JBSA0tG5//rkiims8Z/ot3caipy2T9/wBmlWY/FkrqU4D9OVE232n2ECcLpNlW8qVPdsV/ePyqErStkdPsTFsveXMvEIyjarnVNUomFUMspCC5RLxt+65bSH3UiGA0ybjMrOfb6KjAcpvALAFX97xUYeC23I0SlkJIz/yfkBybPsLOLVMHZEdRN8aBtI5ZrBauqB2ko8EYVydbEEJGJ4UQIDAQAB";

    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8300/determine";


    private Long id;

    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @ResponseBody
    @RequestMapping("/payAlipay/{id}")
    public void alipay(@PathVariable("id") Long id, HttpServletResponse response) throws AlipayApiException, IOException {
        //把dona_id项目id 放在session中
        Long ids= Long.valueOf(id);
        this.id=id;

        OrderEntity orderEntity= orderDao.findByOrderId(ids);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();

        String OrderNum = time + user;

        //调用封装好的方法（给支付宝接口发送请求）
        String str=sendRequestToAlipay(OrderNum, (float) orderEntity.getPrice(), "ghjk");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(str);
    }

    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

    @RequestMapping ("/determine")
    public void determine( HttpServletResponse response) {

        OrderEntity orderEntity=orderDao.findByOrderId(id);
        orderEntity.setPayment(1);
        orderDao.save(orderEntity);
        // 设置响应的内容类型和编码
        response.setContentType("text/html;charset=utf-8");
// 跳转新页面
        response.setHeader("location", "http://localhost:8000/SQE");
// 设置响应码
        response.setStatus(302);


    }


}